<?php

namespace App\Http\Controllers\TK_Api;

use App\Models\Knowledge;
use App\Models\KnowledgePost;
use App\Models\Questions;
use DB;
use Exception;
use Illuminate\Http\JsonResponse;

class KnowledgeController extends ApiBaseController
{
    /**
     * 获取列表
     * @return JsonResponse|object
     */
    public function list() {
        $list = Knowledge::where('level', request('level', 1))
            ->where('courseId', request('courseId'))
            ->where('status', 0);
        if (!empty(request('parentId')))
            $list->where('parentId', request('parentId'));

        if(request('level') == 2) {
            $type = request('type', 1);
            if ($type == 2) {
                $list->with([
                    'post' => function($q) {
                        $q->select('*')
                            ->withCount([
                                'collect as collectCount' => function($query) {
                                    $query->where('postId', DB::raw('tiku_user_knowledge_post.postId'));
                                }
                            ]);
                    }
                ]);
            }else {
                $list->with(['children' => function($q) {
                    $q->select('*')->orderBy('sortNo');
                }]);
            }
        }

        $list = $list->orderBy('sortNo')
            ->select(['id', 'parentId', 'courseId', 'level', 'knowledgeName as name', 'qCount', 'childCount'])
            ->get();


        return $this->restful($list);
    }

    public function questions() {
        $knowledgeId = request('id');
        if (!$knowledgeId) return $this->restful(null, '无效知识点', false);
        $list = Questions::where('thirdKnowledgeId', $knowledgeId)->pluck('id');

        return $this->restful($list);
    }

    /**
     * 获取知识点下文章列表
     * @param $id
     * @return JsonResponse|object
     */
    public function getPosts($id) {
        $knowledge = Knowledge::findOrFail($id);

        $posts = $knowledge->post()->select(['id', 'title', 'knowledgeId'])->get();
        $list = [];

        foreach ($posts as $post) {
            $list[] = [
                'id' => $post->id,
                'title' => $post->title,
                'collectCount' => DB::table('tiku_user_knowledge_post')->where('postId', $post->id)->count()
            ];
        }

        return $this->restful($list);
    }

    /**
     * 获取文章
     * @param $id
     * @return JsonResponse|object
     * @throws Exception
     */
    public function getPost($id) {
        $knowledgePost = KnowledgePost::where('tiku_knowledge_post.id', $id)
            ->leftJoin('tiku_user_knowledge_post', function ($join) {
                $join->on('tiku_knowledge_post.id', '=', 'tiku_user_knowledge_post.postId')
                    ->where('tiku_user_knowledge_post.userId', isset($this->user->id)?$this->user->id:0);
            })
            ->selectRaw('tiku_knowledge_post.*, IF(ISNULL(tiku_user_knowledge_post.id), false, true) AS collected')
            ->first();
        if (!$knowledgePost) throw new Exception('文章不存在', 404);

        return $this->restful($knowledgePost);
    }

    /**
     * 收藏/取消收藏文章
     * @param $id
     * @return JsonResponse|object
     */
    public function postCollect($id) {
        $this->user->knowledgePost()->toggle($id);

        return $this->restful();
    }
}
